package com.bandaotixi.cashier.api.business.impl;

import cn.hutool.core.io.FileUtil;
import com.bandaotixi.cashier.api.business.FileService;
import com.bandaotixi.cashier.api.business.bo.FileInfo;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.InputStream;

/**
 * 本地存储服务类
 *
 */
@Data
@Slf4j
@Component
@ConditionalOnProperty(value = "oss.type", havingValue = "local")
@ConfigurationProperties(prefix = "oss.local")
@RequiredArgsConstructor
public class LocalFileService implements FileService {

    @Value("${oss.local.storage-path}")
    private String storagePath;

    private String getPath(String key) {
        String filePrefix = storagePath.endsWith(File.separator) ? storagePath : storagePath + File.separator;
        return filePrefix + key;
    }

    /**
     * 上传文件方法
     *
     * @return 文件信息
     */
    @Override
    public FileInfo uploadFile(InputStream inputStream, String key, boolean override) {
        String fullFilePath = getPath(key);
        if (override || !FileUtil.exist(fullFilePath)) {
            //  try-with-resource 语法糖自动释放流
            try (InputStream is = inputStream) {
                // 上传文件
                FileUtil.writeFromStream(is, fullFilePath);
            } catch (Exception e) {
                log.error("文件上传失败", e);
                throw new RuntimeException("文件上传失败");
            }
        }
        return get(key);
    }

    /**
     * 删除文件
     *
     * @param filePath 文件完整URL
     * @return 是否删除成功
     */
    @Override
    public boolean deleteFile(String filePath) {
        //判断文件是否为空
        if (filePath == null || filePath.isEmpty()) {
            return false;
        }
        // 判断filepath是否为文件夹
        if (FileUtil.isDirectory(storagePath + filePath)) {
            // 禁止删除文件夹
            return false;
        }
        // 删除文件
        return FileUtil.del(storagePath + filePath);
    }

    @Override
    public boolean exists(String key) {
        String fullFilePath = getPath(key);
        return FileUtil.exist(fullFilePath);
    }

    @Override
    public FileInfo get(String key) {
        // 获取文件访问路径，因为这里是本地存储，所以直接返回文件的相对路径，需要前端自行处理访问前缀
        FileInfo fileInfo = new FileInfo();
        fileInfo.setName(FileUtil.getName(key));
        fileInfo.setUrl(key);
        return fileInfo;
    }
}
